<template>
  <div class="user-profile-page">
    <van-nav-bar
      left-arrow
      @click-left="$router.back()"
      title="个人信息"
    ></van-nav-bar>
    <van-cell-group>
      <van-uploader
        :before-read="beforeRead"
        :after-read="afterRead"
        style="width:100%"
      >
        <van-cell is-link title="头像" center>
          <van-image slot="default" fit="cover" round :src="userInfo.photo" />
        </van-cell>
      </van-uploader>
      <van-cell
        is-link
        title="昵称"
        :value="userInfo.name"
        @click="nameClick"
      />
    </van-cell-group>
    <van-cell-group style="margin-top:12px">
      <!-- 0:男  1：女  2：保密 -->
      <van-cell
        @click="genderClick"
        is-link
        title="性别"
        :value="{ 0: '男', 1: '女', 2: '保密' }[userInfo.gender]"
      />
      <!-- 过滤器：
      作用：数据转换
      特点：不能使用this,只能在{{}} v-bind
       -->
      <van-cell
        @click="birthdayClick"
        is-link
        title="生日"
        :value="userInfo.birthday | formatTime"
      />
    </van-cell-group>
    <div class="logout" @click="logout">
      <span>退出登录</span>
    </div>
    <!-- 性别 修改弹框
    van-action-sheet
      v-model="是否显示"
      :actions=[{name:选项文本,disabled:是否禁用}]
      cancel-text=取消文本
      @select="点击选项后触发"
      @cancel="点击取消时触发"
      close-on-click-action:点击选项时自动关闭弹窗组件
    -->

    <van-action-sheet
      v-model="showGender"
      :actions="actions"
      cancel-text="取消"
      @cancel="showGender = false"
      @select="genderSelect"
    >
    </van-action-sheet>
    <van-popup v-model="showDate" position="bottom">
      <van-datetime-picker
        v-model="currentTime"
        title="选择生日"
        type="date"
        :min-date="minDate"
        :max-date="maxDate"
        @cancel="showDate = false"
        @confirm="dateConfirm"
      >
      </van-datetime-picker>
    </van-popup>
    <Edit
      ref="edit"
      @editUserInfo="editUserInfo"
      :editShow.sync="editShow"
    ></Edit>
  </div>
</template>
<script>
import { mapState, mapMutations } from 'vuex'
import dayjs from 'dayjs'
import { userProfilePatch, userPhotoPatch } from '@/api/user.js'
import Edit from './components/edit.vue'
export default {
  name: 'UserProfilePage',
  components: {
    Edit
  },
  filters: {
    formatTime (time) {
      return dayjs(time).format('YYYY-MM-DD')
    }
  },
  data () {
    return {
      editShow: false,
      showGender: false,
      currentTime: new Date(),
      showDate: false,
      minDate: new Date('1950-01-01'),
      maxDate: new Date(),
      actions: [
        {
          name: '男',
          value: 0
        },
        {
          name: '女',
          value: 1
        }
      ]
    }
  },
  computed: {
    ...mapState('user', ['userInfo'])
  },
  created () {
    this.$store.dispatch('user/getUserInfo')
  },
  methods: {
    nameClick () {
      this.editShow = true
      this.$refs.edit.inputValue = this.userInfo.name
    },
    // 退出点击
    /*
    确定框
    this.$dialog.alert().then(()=>{})
    this.$dialog.confirm({title:标题,message:内容}).then(()=>{确定点击}).catch(()=>{取消点击})
    */
    ...mapMutations('user', ['setToken']),
    //  ...mapMutations(['user/setToken']),
    logout () {
      this.$dialog
        .confirm({ title: '提示', message: '您确定退出该网站吗？' })
        .then(() => {
          this.setToken('')
          this.$router.push('/')
          this.$toast.success('退出成功')
        })
        .catch(() => {})
    },
    // 选择性别
    // async genderSelect (obj) {
    //   this.showGender = false
    //   // 调用修改个人资料api
    //   await userProfilePatch({
    //     [obj.key]: obj.value
    //   })
    //   // 调用vuex内的mutations方法修改属性
    //   this.$store.commit('user/setUserOther', {
    //     key: obj.key,
    //     value: obj.value
    //   })
    //   //
    //   this.$toast.success('修改成功')
    // },
    async genderSelect (item) {
      console.log(item)
      this.showGender = false
      this.editUserInfo({
        key: 'gender',
        value: item.value
      })
    },
    async editUserInfo (obj) {
      await userProfilePatch({
        [obj.key]: obj.value
      })
      this.$store.commit('user/setUserOther', {
        key: obj.key,
        value: obj.value
      })
      this.$toast.success('修改成功')
    },
    // 性别点击
    genderClick () {
      this.showGender = true
      this.actions[this.userInfo.gender].disabled = true
      this.actions[1 - this.userInfo.gender].disabled = false
    },
    // 生日点击
    birthdayClick () {
      this.showDate = true
      this.currentTime = new Date(this.userInfo.birthday)
    },
    // 选择生日后点击确认
    async dateConfirm () {
      this.showDate = false
      this.editUserInfo({
        key: 'birthday',
        value: this.currentTime
      })
    },
    async afterRead (res) {
      console.log(res)
      const _formdata = new FormData()
      _formdata.append('photo', res.file)
      const response = await userPhotoPatch(_formdata)
      this.$store.commit('user/setUserOther', {
        key: 'photo',
        value: response.data.photo
      })
      this.$toast.success('修改成功')
      console.log(response)
    },
    beforeRead (file) {
      const isImg = file.type === 'image/png' || file.type === 'image/jpeg'
      const limit1m = file.size / 1024 / 1024 < 1
      if (!isImg) {
        this.$toast.fail('请上传png与jpg图片格式')
      }
      if (!limit1m) {
        this.$toast.fail('请上传1m以内的图片')
      }
      return isImg && limit1m
    }
  }
}
</script>
<style lang="less" scoped>
.user-profile-page {
  background: #f8f8f8;
  .van-image {
    display: block;
    float: right;
    width: 30px;
    height: 30px;
  }
  .van-cell__title {
    width: 50px;
    flex: none;
  }
}
.logout {
  text-align: center;
  position: absolute;
  left: 0;
  bottom: 30px;
  width: 100%;
  color: @geek-color;
}
::v-deep .van-uploader__input-wrapper {
  width: 100%;
}
</style>
